//
//  PostUploadImageDataBase.m
//  WULIHH
//
//  Created by tang on 16/5/3.
//  Copyright © 2016年 tang. All rights reserved.
//

#import "PostUploadImageDataBase.h"
#import "FMDB.h"


@interface PostUploadImageDataBase ()
{
    FMDatabase     *db;
    int             totalInt;
}

@end

@implementation PostUploadImageDataBase


sloganIntence(PostUploadImageDataBase);



//打开数据库
- (void)openDataBase
{
    
    //创建编辑图片数据库
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentDirectory = [paths objectAtIndex:0];
        NSLog(@"%@", documentDirectory);
    NSString *dbPath = [documentDirectory stringByAppendingPathComponent:@"MyDatabase.db"];
    db = [FMDatabase databaseWithPath:dbPath] ;
    if (![db open]) {
        NSLog(@"Could not open db");
        //        return ;
    }
    else
    {
        [db executeUpdate:@"DROP TABLE IF EXISTS uploadWorkImageList"];
        [db executeUpdate:@"CREATE TABLE IF NOT EXISTS uploadWorkImageList (ImageData blob, CellIndex integer, qipaoDic blob, postView blob, withConnectID integer)"];
    }
    
//    [db rollback];
    
}


//插入数据(事物写入)
- (void)insertID:(NSString *)ISString withUpLoadImage:(NSData *)uploadImageData withConnectID:(NSString *)connectIDString withShowImage:(NSData *)showImageData
{
    
}


- (void)insertModelwithImageArray:(NSArray *)imageArray withCOnnectIDArray:(NSArray *)IDArray
{
    totalInt = (int)imageArray.count;
    NSLog(@"%d", totalInt);
    
    [db beginTransaction];
    BOOL isRollBack = NO;
    @try {
        for (int i = 0; i<imageArray.count; i++) {
            
//            NSLog(@"%@", [NSString stringWithFormat:@"%d", i]);
            BOOL a = [db executeUpdate:@"INSERT INTO uploadWorkImageList (ImageData, CellIndex, postView, withConnectID) VALUES (?,?,?,?)", [imageArray objectAtIndex:i], [NSString stringWithFormat:@"%d", i], [imageArray objectAtIndex:i], [NSString stringWithFormat:@"%d", [[IDArray objectAtIndex:i] intValue]]];
            
            if (!a) {
                NSLog(@"插入失败1");
            }
            else
            {
                NSLog(@"charuchenggong");
            }
        }
    }
    @catch (NSException *exception) {
        isRollBack = YES;
        [db rollback];
    }
    @finally {
        if (!isRollBack) {
            [db commit];
        }
    }
    
}




//添加图片
- (void)addPhotoWithImageArray:(NSArray *)imageArray withConnectIDArray:(NSArray *)IDArray
{
    [db beginTransaction];
    BOOL isRollBack = NO;
    @try {
        for (int i = totalInt; i<imageArray.count+totalInt; i++) {
            
//            NSLog(@"%@", [NSString stringWithFormat:@"%d", i]);
            BOOL a = [db executeUpdate:@"INSERT INTO uploadWorkImageList (ImageData, CellIndex, postView, withConnectID) VALUES (?,?,?,?)", [imageArray objectAtIndex:i-totalInt], [NSString stringWithFormat:@"%d", i], [imageArray objectAtIndex:i-totalInt], [NSString stringWithFormat:@"%d", [[IDArray objectAtIndex:i-totalInt] intValue]]];
            
            if (!a) {
//                NSLog(@"插入失败1");
            }
            else
            {
//                NSLog(@"charuchenggong");
            }
        }
    }
    @catch (NSException *exception) {
        isRollBack = YES;
        [db rollback];
    }
    @finally {
        if (!isRollBack) {
            [db commit];
        }
    }
    
    totalInt = totalInt+(int)imageArray.count;

}









//读取图片信息
- (void)readImageWithSelect:(NSString *)selectString wirhInfo:(getImageInfo)callBack
{
    FMResultSet *rs = [db executeQuery:@"SELECT ImageData , qipaoDic FROM uploadWorkImageList WHERE CellIndex = ?", selectString];
    if ([rs next])
    {
        NSData *data = [rs dataForColumn:@"ImageData"];
//        NSLog(@"++++++++---%@", data);
        NSData *data2 = [rs dataForColumn:@"qipaoDic"];
         NSDictionary *dic = nil;
        if (data2 == nil)
        {
//            NSLog(@"1111111111");
        }
        else
        {
//            NSLog(@"2222222222");
            dic = [NSJSONSerialization JSONObjectWithData:data2 options:NSJSONReadingMutableContainers error:nil];
        }
        
       
        
        callBack(data, dic);
    }
    else
    {
        
    }
}





//读取选中照片保存上一张照片
- (void)readCurrentImageWithSelect:(NSString *)currentString withLastString:(NSString *)lastString withLastIMage:(NSData *)lastImageData withLastQiapo:(NSDictionary *)lasQipaoInfo withCallBack:(getImageSelectInfo)GetIMageBack
{

    NSData *qipaoData = nil;
    if (lasQipaoInfo == nil)
    {
        
    }
    else
    {
        qipaoData = [NSJSONSerialization dataWithJSONObject:lasQipaoInfo options:NSJSONWritingPrettyPrinted error:nil];
    }
    
    BOOL rs = [db executeUpdate:@"UPDATE uploadWorkImageList SET postView = ?, qipaoDic = ? WHERE CellIndex = ?", lastImageData, qipaoData, lastString];
    
    if (rs)
    {
        FMResultSet *rsResult = [db executeQuery:@"SELECT ImageData , qipaoDic FROM uploadWorkImageList WHERE CellIndex = ?", currentString];
        if ([rsResult next])
        {
            NSData *data1 = [rsResult dataForColumn:@"ImageData"];
            NSData *data2 = [rsResult dataForColumn:@"qipaoDic"];
//            NSLog(@"%@", data2);
            if (data2 == nil)
            {
                GetIMageBack(data1, nil);
            }
            else
            {
                GetIMageBack(data1, [NSJSONSerialization JSONObjectWithData:data2 options:NSJSONReadingMutableContainers error:nil]);
            }
//

        }
        else
        {
//            NSLog(@"%@", [rsResult resultDict]);
        }
    }
    else
    {
        NSLog(@"shiban");
    }
}



//读取所有信息
- (void)readAllImageFromDB:(getAllImageInfo)AllCallBack
{
//    NSMutableArray *sourceimageArray = [NSMutableArray new];
//    NSMutableArray *postImageArray = [NSMutableArray new];
//    NSMutableArray *connectIDArray = [NSMutableArray new];
    
    NSMutableArray *totalArray = [NSMutableArray new];
    
    FMResultSet *rsResult = [db executeQuery:@"SELECT ImageData , withConnectID, postView FROM uploadWorkImageList"];
    while ([rsResult next])
    {
//        [sourceimageArray addObject:[rsResult dataForColumn:@"ImageData"]];
//        [postImageArray addObject:[rsResult dataForColumn:@"postView"]];
//        [connectIDArray addObject:[NSString stringWithFormat:@"%d", [rsResult intForColumn:@"CellIndex"]]];
        NSDictionary *dic = @{@"source":[rsResult dataForColumn:@"ImageData"],
                              @"postdata":[rsResult dataForColumn:@"postView"],
                              @"connectid":[NSString stringWithFormat:@"%d", [rsResult intForColumn:@"withConnectID"]]};
        [totalArray addObject:dic];
    }
    
    AllCallBack(totalArray, nil, nil);
}


@end
